package edu.office.applicationRepository;

import edu.office.entities.School;
import edu.office.entities.Student;
import edu.office.entities.Studentschedule;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;


@Named("studentscheduleRepositoryA")
@ApplicationScoped
public class StudentscheduleRepository extends ApplicationCommonRepository<Studentschedule> {

    @Inject
     StudentRepository studentRepository;


    public List<Studentschedule> getStudentscheduleList(School school) {
        List<Studentschedule> result = new ArrayList<>();
        Calendar current = Calendar.getInstance();
        String currentTime = current.get(Calendar.YEAR) + "-" 
                + (current.get(Calendar.MONTH) + 1)
                + "-" + current.get(Calendar.DAY_OF_MONTH);
        //上面的月这所以加1，是因为1月对应的是0
        //SELECT * FROM LEARNING.STUDENTSCHEDULE where endtime>date('2018-05-01') and userid=439;
        if (null != school && null != school.getID()) {
            studentRepository.find("SCHOOL_ID",school.getID()).list().forEach((student) -> result.addAll(find(
                    "SELECT * FROM STUDENTSCHEDULE where endtime>date('"
                    + currentTime + "')  and userid=" + student.getId()
            ).list()));
        }
        return result;
    }

    public void Create(Set<Student> studentSet, Studentschedule newstudentschedule) {
        for (Student student : studentSet) {
            List<Studentschedule> existedScheduleSet = list("USERID", student.getId());
            boolean existed = false;
            for (Studentschedule studentSchedule : existedScheduleSet) {
                if (studentSchedule.getENDTIME().isAfter(newstudentschedule.getENDTIME())
                        && studentSchedule.getBELONGCLASSID().equals(newstudentschedule.getBELONGCLASSID())) {
                    existed = true;
                }
            }
            if (!existed) {
                Studentschedule studentschedule = new Studentschedule();
                studentschedule.setUSERID(student.getId());
                studentschedule.setSTARTTIME(newstudentschedule.getSTARTTIME());
                studentschedule.setENDTIME(newstudentschedule.getENDTIME());
                studentschedule.setBELONGCLASSID(newstudentschedule.getBELONGCLASSID());
                create(studentschedule);
            }
        }
    }
}
